package com.whiteape.book.core.parser;

import com.whiteape.book.core.manager.ParserManager;
import com.whiteape.book.model.bo.RuleBo;
import com.whiteape.book.model.bo.SearchResultBo;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.SiteSourceBean;
import com.whiteape.book.model.dto.SiteSourceSearchBean;
import com.whiteape.book.model.dto.SiteSourceSearchResultBean;
import com.whiteape.book.utils.URLUtils;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Single;

public class SearchResultParser {

    public static Single<List<SearchResultBo>> parse(SiteSourceBean siteSourceBean, String currentUrl, String html) {

        List<SearchResultBo> searchResultBoList = new ArrayList<>();
        if (siteSourceBean == null || StringUtils.isEmpty(html)) {
            return Single.create(emitter -> emitter.onSuccess(searchResultBoList));
        }
        return Single.create(emitter -> {

            try {
                SiteSourceSearchBean siteSourceSearchBean = siteSourceBean.getSearch();
                //TODO search rule需要校验有值的：detailUrl, title, author,不合格的不入库
                SiteSourceSearchResultBean searchRuleBean = siteSourceSearchBean.getResult();
                String listRule = searchRuleBean.getList();

                //TODO 认定取list的都只有一个？
                List list = ParserManager.getElementList(currentUrl, html, listRule);
                if (list == null || list.size() == 0) {
//                emitter.onError(new Throwable("list not found"));
                    //可能只有一条，直接跳转到书籍详情页面了,在这里做判断

                    //TODO如果直接到详情页的，其实可能同时拿到章节信息，加快下一步点击进入详情的速度
//                boolean parseCatalogTogether = StringUtils.isEmpty(siteSourceBean.getMediaInfoDetailRule().getCatalogUrl());
                    parseMediaInfoDetail(siteSourceBean, searchResultBoList, currentUrl, html);

                    emitter.onSuccess(searchResultBoList);
                    return;
                }
                for (Object ele : list) {

                    String doc = ParserManager.getElementString(ele);

                    SearchResultBo infoBean = new SearchResultBo();
                    HashMap<String, String> varMap = new HashMap<>();
                    infoBean.setVarMap(varMap);
                    String detailRule = searchRuleBean.getDetailUrl();
                    //TODO text or attr?
                    String detailUrl = ParserManager.parseOne(currentUrl, doc, detailRule, varMap);
                    if (StringUtils.isEmpty(detailUrl)) {
                        continue;
                    }
                    String searchUrl = siteSourceBean.getSearch().getUrl();
                    if (!searchUrl.startsWith("http")) {
                        searchUrl = URLUtils.getAbsolutePath(siteSourceBean.getSiteHostUrl(), searchUrl);
                        siteSourceBean.getSearch().setUrl(searchUrl);
                    }
                    detailUrl = URLUtils.getAbsolutePath(searchUrl, detailUrl);
                    infoBean.setDetailUrl(detailUrl);

                    ///////author
                    String authorRule = searchRuleBean.getAuthor();
                    String author = ParserManager.parseOne(currentUrl, doc, authorRule, varMap);
                    infoBean.setAuthor(author);

                    ///title
                    String titleRule = searchRuleBean.getTitle();
                    String title = ParserManager.parseOne(currentUrl, doc, titleRule, varMap);
                    if (StringUtils.isEmpty(title)) {
                        continue;
                    }
                    infoBean.setTitle(title);

                    String coverUrl = ParserManager.parseOne(currentUrl, doc, searchRuleBean.getCoverUrl(), varMap);
                    if (!coverUrl.isEmpty()) {
                        coverUrl = URLUtils.getAbsolutePath(currentUrl, coverUrl);
                    }
                    infoBean.setCoverUrl(coverUrl);
                    ///.........others
                    infoBean.setMediaType(siteSourceBean.getSiteType());
                    infoBean.setCategory(ParserManager.parseOne(currentUrl, doc, searchRuleBean.getCategory(), varMap));
                    infoBean.setDesc(ParserManager.parseOne(currentUrl, doc, searchRuleBean.getDesc(), varMap));
                    infoBean.setLastChapter(ParserManager.parseOne(currentUrl, doc, searchRuleBean.getLastChapter(), varMap));
                    infoBean.setLastUpdated(ParserManager.parseOne(currentUrl, doc, searchRuleBean.getLastUpdated(), varMap));
                    infoBean.setState(ParserManager.parseOne(currentUrl, doc, searchRuleBean.getState(), varMap));
                    infoBean.setWordCount(ParserManager.parseOne(currentUrl, doc, searchRuleBean.getWordCount(), varMap));


                    infoBean.setSiteSourceBean(siteSourceBean);

                    searchResultBoList.add(infoBean);

                }

                emitter.onSuccess(searchResultBoList);
//            emitter.onComplete();
            } catch (Exception e) {
                e.printStackTrace();
                emitter.onSuccess(searchResultBoList);
            }

        });


    }

    private static void parseMediaInfoDetail(SiteSourceBean siteSourceBean, List<SearchResultBo> searchResultBoList, String currentUrl, String html) {

        HashMap<String, String> varMap = new HashMap<>();
        CollectionMediaBean mediaBean = MediaInfoParser.parseDirectly(siteSourceBean, currentUrl, varMap, html);
        if (!"".equals(mediaBean.getAuthor()) && !"".equals(mediaBean.getTitle())) {
            //真的是直接跳转到书籍详情页面了，封装成搜索结果来
            SearchResultBo searchResultBo = new SearchResultBo();
            searchResultBo.setMediaType(siteSourceBean.getSiteType());
            searchResultBo.setSiteSourceBean(siteSourceBean);
            searchResultBo.setDetailUrl(currentUrl);
            searchResultBo.setAuthor(mediaBean.getAuthor());
            searchResultBo.setTitle(mediaBean.getTitle());
            searchResultBo.setCategory(mediaBean.getCategory());
            searchResultBo.setCoverUrl(mediaBean.getCoverUrl());
            searchResultBo.setDesc(mediaBean.getDesc());
            searchResultBo.setLastChapter(mediaBean.getLastChapter());
            searchResultBo.setLastUpdated(mediaBean.getLastUpdated());
            searchResultBo.setState(mediaBean.getState());
            searchResultBo.setWordCount(mediaBean.getWordCount());
            searchResultBo.setVarMap(varMap);
            searchResultBoList.add(searchResultBo);

        }
    }

}
